import React, { Component } from 'react'
import { Form, Icon, Input, Button, Alert } from 'antd'
import { connect } from 'react-redux'
import { withRouter, Link } from 'react-router-dom'
import * as loginAction from '../actions/login-action'
import { bindActionCreators } from 'redux'
import * as Utils from '../utils'
import {
	TOKEN,
} from '../constants'

import '../style/login.css'

const FormItem = Form.Item

/*
* 装饰器模式, 具体查看 es6 语法
* */
@connect(
	// 把 redux 的 state, 转变为页面的 props
	state => {
		// 得到经过 reducer 后的 state 结果
		const { loginReducer } = state
		const loginState = loginReducer.toJS()
		return ({
			hasLogin: loginState.hasLogin,
			errorMsg: loginState.errorMsg,
			errorCode: loginState.errorCode,
		})
	},
	dispatch => ({
		loginActions: bindActionCreators({...loginAction}, dispatch),
	})
)
class Login extends Component {

	constructor(props) {
		super(props)
		this.state = {
			showErrMsg: false,
		}
	}

	// 如果 sessionStorage 已经有 token, 说明已经成功登录, 直接跳进入系统
	componentWillMount() {
		if(!!Utils.getItem(TOKEN)) {
			this.props.history.push('/user/:id')
		}
	}

	// 当页面的 state 发生变化时触发
	componentWillReceiveProps(nextProps) {
		let { hasLogin, errorMsg, errorCode } = nextProps
		if (hasLogin && !!Utils.getItem(TOKEN)) {
			// console.log('Login status: Welcome!')
			this.props.history.push('/user/:id')
		} else {
			if(!!errorMsg) {
				// message.error("Incorrect username or password.")
				this.setState({
					showErrMsg: true,
					errorMsg,
					errorCode,
				})
			}
		}
	}

	/*
	 * form 表单提交事件
	 * */
	handleSubmit = (e) => {
		e.preventDefault();
		this.props.form.validateFields((err, values) => {
			if (!err) {
				let user = {
					userId: values.userId,
					password: values.password,
				}
				this.props.loginActions.loginAction('http://localhost:8848/vtg/auth', 'POST', user)
			}
		})
	}

	showErrMsg = () => {
		return (
			this.state.showErrMsg ?
			<Alert
				message="Error"
				description={this.state.errorCode===500?this.state.errorMsg:"Incorrect username or password."}
				type="error"
				showIcon
			/>
				:
			null
		)
	}

	clearErrMsg = (e) => this.props.loginActions.clearErrMsgAction()

	render() {
		const { getFieldDecorator } = this.props.form
		return (
			<div>
				{this.showErrMsg()}
				<div style={{ justifyContent: 'center', alignItems: 'left', display: 'flex' }}>
					<Form onSubmit={this.handleSubmit} className="login-form">
						<FormItem>
							{getFieldDecorator('userId', {
								rules: [{ required: true, message: 'Please input your user id!' }],
							})(
								<Input prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />} placeholder="User Id" />
							)}
						</FormItem>
						<FormItem>
							{getFieldDecorator('password', {
								rules: [{ required: true, message: 'Please input your password!' }],
							})(
								<Input prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />} type="password" placeholder="Password" />
							)}
						</FormItem>
						<FormItem>
							<a className="login-form-forgot" href="">Forgot password</a>
							<Button type="primary" htmlType="submit" className="login-form-button">
								Log in
							</Button>
							Or <Link to="/registration" onClick={this.clearErrMsg}>register now!</Link>
						</FormItem>
					</Form>
				</div>
			</div>
		)
	}
}

export default withRouter(Form.create()(Login))
